package com.yayo.mangement.utils;

import java.security.MessageDigest;
import java.util.Random;

public class SaltEncryptionUtils {

    /**
     * 固定盐值
     */
    public static final String NORMAL_SALT = "@Yayo";

    /**
     * 随机盐值组
     */
    private static char[] ch = {'5', '6', 'T', 'U', '0', '1', 'V', 'o', 'p', 't', 'u', 'W', 'x', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
            'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'z', 'w', 'X', 'y', 'v', 'S', 'Y', 'g', 'h', 'i', 'q', 'r', 's', '2', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', '3', '4',
            'j', 'I', 'J', 'K', 'k', 'l', 'm', 'n', 'F', 'G', 'H'};

    /**
     * 将密码加盐加密
     * @param password 源密码
     * @param salt 盐值
     * @return
     */
    public static String encryption(String password, String salt) {
        byte[] bArr = (NORMAL_SALT + password + salt).getBytes();
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA");
            byte[] sha_byte = sha.digest(bArr);
            StringBuffer hexValue = new StringBuffer();
            for (byte b : sha_byte) {
                //将其中的每个字节转成十六进制字符串：byte类型的数据最高位是符号位，通过和0xff进行与操作，转换为int类型的正整数。
                String toHexString = Integer.toHexString(b & 0xff);
                hexValue.append(toHexString.length() == 1 ? "0" + toHexString : toHexString);
            }
            return hexValue.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取随机盐值
     * @return
     */
    public static String getRandomSalt() {
        String salt = "";
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            salt += ch[random.nextInt(ch.length)];
        }
        return salt;
    }

}
